package com.taskflow.service;

import com.taskflow.common.PageResult;
import com.taskflow.dto.TaskQueryDTO;
import com.taskflow.entity.DownloadTask;
import com.taskflow.mapper.DownloadTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 下载任务Service
 */
@Service
public class DownloadTaskService {

    @Autowired
    private DownloadTaskMapper taskMapper;

    @Autowired
    private TaskSchedulerService schedulerService;

    @Transactional
    public Long createTask(DownloadTask task) {
        if (task.getStatus() == null) {
            task.setStatus(1);
        }
        taskMapper.insert(task);
        
        // 如果任务是启用状态，添加到调度器
        if (task.getStatus() == 1) {
            schedulerService.scheduleTask(task);
        }
        
        return task.getId();
    }

    @Transactional
    public void updateTask(DownloadTask task) {
        DownloadTask oldTask = taskMapper.selectById(task.getId());
        if (oldTask == null) {
            throw new RuntimeException("任务不存在");
        }
        
        taskMapper.update(task);
        
        // 更新调度器
        schedulerService.removeTask(task.getId());
        if (task.getStatus() == 1) {
            schedulerService.scheduleTask(task);
        }
    }

    @Transactional
    public void deleteTask(Long id) {
        schedulerService.removeTask(id);
        taskMapper.deleteById(id);
    }

    public DownloadTask getTaskById(Long id) {
        return taskMapper.selectById(id);
    }

    public PageResult<DownloadTask> getTaskList(TaskQueryDTO query) {
        List<DownloadTask> list = taskMapper.selectList(query);
        Long total = taskMapper.selectCount(query);
        return new PageResult<>(list, total, query.getCurrent(), query.getSize());
    }

    @Transactional
    public void updateTaskStatus(Long id, Integer status) {
        DownloadTask task = taskMapper.selectById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        taskMapper.updateStatus(id, status);
        
        // 更新调度器
        schedulerService.removeTask(id);
        if (status == 1) {
            task.setStatus(status);
            schedulerService.scheduleTask(task);
        }
    }

    public List<DownloadTask> getEnabledTasks() {
        return taskMapper.selectEnabledTasks();
    }

    public List<DownloadTask> getAllTasks() {
        return taskMapper.selectAllTasks();
    }
}

